﻿using CacheExtensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;

namespace SignalRExtensions
{
    public static class SignalRExtension
    {
        public static void AddSignalR(this IServiceCollection services, IConfiguration configuration)
        {

            var config = configuration.GetSection("Cache").Get<CacheConfig>() ?? new CacheConfig();

            var queryPaths = configuration.GetSection("Auth").GetSection("QueryPaths").Get<string[]>();
            if (!(queryPaths != null && queryPaths.Length > 0))
            {
                return;
            }

            if (config.Type == CacheType.Redis && config.Redis != null)
            {
                services.AddSignalR(hubOptions =>
                {
                    hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(15);
                    hubOptions.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
                }).AddStackExchangeRedis(config.Redis.ConnectionString, options =>
                {
                    options.Configuration.ChannelPrefix = new RedisChannel(config.Prefix, RedisChannel.PatternMode.Auto);
                });
            }
            else
            {
                services.AddSignalR(hubOptions =>
                {
                    hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(15);
                    hubOptions.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
                });
            }
        }


        public static void MapMessageHub(this WebApplication app)
        {
            
            var queryPaths = app.Configuration.GetSection("Auth").GetSection("QueryPaths").Get<string[]>();
            if ((queryPaths != null && queryPaths.Length > 0))
            {
                app.MapHub<MessageHub>("/MessageHub");
            }
           
        }

     
    }
}
